package Bean;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author jianjun
 * @Describe
 * @creat 2021-12-30-22:20
 */
public class Cart {
    //    private Integer totalCount;     //总商品数量
//    private BigDecimal totalPrice;      //总商品金额
    private Map<Integer, CartItem> items = new LinkedHashMap<>();   //购物车商品

    public Cart() {
    }

    @Override
    public String toString() {
        return "Cart{" +
                "totalCount=" + getTotalCount() +
                ", totalPrice=" + getTotalPrice() +
                ", items=" + items +
                '}';
    }

    //获取购物车商品总数
    public Integer getTotalCount() {
        int totalCount = 0;
        for (Map.Entry<Integer, CartItem> entry : items.entrySet()) {
            totalCount += entry.getValue().getCount();
        }
        return totalCount;
    }

    //获取购物车所有商品的价格总和
    public BigDecimal getTotalPrice() {
        BigDecimal totalPrice = new BigDecimal(0);
        for (Map.Entry<Integer, CartItem> entry : items.entrySet()) {
            totalPrice = totalPrice.add(entry.getValue().getTotalPrice());
        }
        return totalPrice;
    }
    //添加图书至购物车
    public void addItem(CartItem cartItem) {
        CartItem item = items.get(cartItem.getId());
        if (item == null) {
            items.put(cartItem.getId(), cartItem);
        } else {
            item.setCount(item.getCount() + 1);
            item.setTotalPrice(item.getPrice().multiply(new BigDecimal(cartItem.getCount())));
        }
    }

    //删除购物车的某个项
    public void deleteItem(Integer id) {
        items.remove(id);
    }

    //清空购物车
    public void clear() {
        items.clear();
    }

    //修改商品数量
    public void updateCount(Integer id, Integer count) {
        CartItem cartItem = items.get(id);
        if (cartItem != null) {
            cartItem.setCount(count);
            cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(count)));
        }
    }

    public Map<Integer, CartItem> getItems() {
        return items;
    }
}
